package com.huangmingfu;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: 黄名富
 * @Description: 观察者模式
 */
public class ObserverPattern {

    public static void main(String[] args) {
        Subject subject = new School();

        Observer observer1 = new Teacher();
        Observer observer2 = new Student();
        subject.attach(observer1);
        subject.attach(observer2);

        subject.notifyObserverList("快高考啦！");
        subject.notifyObserverList("六一放假");
    }

    private static abstract class Subject {
        protected final Set<Observer> observerList = new HashSet<>();

        public void attach(Observer observer) {
            observerList.add(observer);
        }

        public void detach(Observer observer) {
            observerList.remove(observer);
        }

        public void notifyObserverList(String content) {
            beforeNotify(content);
            for (Observer observer : observerList) observer.update(content);
            afterNotify(content);
        }

        public abstract void beforeNotify(String content);

        public abstract void afterNotify(String content);

    }

    private static class School extends Subject {

        @Override
        public void beforeNotify(String content) {
            System.out.println("通知时间：" + new Date());
        }

        @Override
        public void afterNotify(String content) {
            System.out.println("通知完成");
        }
    }

    private interface Observer {
        void update(String content);
    }

    private static class Student implements Observer {
        @Override
        public void update(String content) {
            if (content.contains("放假")) System.out.println("学生，耶耶耶！");
            else System.out.println("学生，哦哦哦");
        }
    }

    private static class Teacher implements Observer {

        @Override
        public void update(String content) {
            System.out.println("老师，收到：" + content);
        }
    }

}
